#include <opencv2/opencv.hpp> // For printf()

using namespace std;
using namespace cv;

// Initialize a sub funcion using after main
CvRect detectFaceInImage( IplImage *inputImg, CvHaarClassifierCascade* cascade);

int mainfd(int argc, char* argv[])
{
    CvPoint pt1, pt2;    // For draw rectangle
    // Check the input is correct when call executable file
    /* if (argc != 2)
    {
    printf("Usage: faceDetector.exe <imagename>\n");
    exit(-1);
    }*/

    //char * imgName = argv[1];    // Copy the second input as the image name
    char * imgName = "D:\\lena.png";
    // Load image
    IplImage* inputImg = cvLoadImage(imgName, CV_LOAD_IMAGE_UNCHANGED);
    if (!inputImg) {
        printf("Error: Could not open the image file! \n");
        exit(-1);
    }

    // Haar Cascade file, used for Face Detection.
    // Note: you could change this directory as your installed OpenCV2.1 location
    char *faceCascadeFilename = "E:/opencv/opencv_c/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml";
    // Load the HaarCascade classifier for face detection.
    CvHaarClassifierCascade* faceCascade;
    faceCascade = (CvHaarClassifierCascade*)cvLoad(faceCascadeFilename, 0, 0, 0);
    if( !faceCascade ) {
        printf("Couldnt load Face detector '%s'\n", faceCascadeFilename);
        exit(-1);
    }

    // Perform face detection on the input image, using the given Haar classifier
    CvRect faceRect = detectFaceInImage(inputImg, faceCascade);
    // Make sure a valid face was detected then draw the rect location.
    if (faceRect.width > 0)
    {
        printf("Detected a face at (%d,%d)!\n", faceRect.x, faceRect.y);

        // Get the pointer of the face rectangle
        pt1.x = faceRect.x;
        pt2.x = faceRect.x + faceRect.width;
        pt1.y = faceRect.y;
        pt2.y = faceRect.y + faceRect.height;

        // Draw the rectangle in the input image
        cvRectangle( inputImg, pt1, pt2, CV_RGB(255,0,0), 2, 8, 0 );

        // Show the detected face image on the screen.
        cvNamedWindow("Detected face", CV_WINDOW_AUTOSIZE);
        // Show the image in the window named "Detected face", you could change as you like
        cvShowImage( "Detected face", inputImg );

        // Wait for the user to press something on the graphical window.
        // Note: cvWaitKey() is needed for time to draw on the screen.
        cvWaitKey(0);

        // Free the resources.
        cvDestroyWindow("Detected face");
        cvReleaseImage( &inputImg );
    }

    // Free the Face Detector resources when the program is finished
    cvReleaseHaarClassifierCascade( &faceCascade );
    return 0;
}

// Perform face detection on the input image, using the given Haar Cascade.
// Returns a rectangle for the detected region in the given image.
CvRect detectFaceInImage(IplImage *inputImg, CvHaarClassifierCascade* cascade)
{
    // Smallest face size.
    CvSize minFeatureSize = cvSize(20, 20);
    // Only search for 1 face.
    int flags = CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH;
    // How detailed should the search be.
    float search_scale_factor = 1.1f;
    IplImage *detectImg;
    IplImage *greyImg = 0;
    CvMemStorage* storage;
    CvRect rc;
    //double t;
    CvSeq* rects;
    CvSize size;
    int nFaces;
    //int i, ms;
    storage = cvCreateMemStorage(0);
    cvClearMemStorage( storage );

    // If the image is color, use a greyscale copy of the image.
    detectImg = (IplImage*)inputImg;
    if (inputImg->nChannels > 1) {
        size = cvSize(inputImg->width, inputImg->height);
        greyImg = cvCreateImage(size, IPL_DEPTH_8U, 1 );
        cvCvtColor( inputImg, greyImg, CV_BGR2GRAY );
        detectImg = greyImg; // Use the greyscale image.
    }

    // Detect all the faces in the greyscale image.
    //t = (double)cvGetTickCount();
    rects = cvHaarDetectObjects( detectImg, cascade, storage,
        search_scale_factor, 3, flags, minFeatureSize);
    //t = (double)cvGetTickCount() - t;
    //ms = cvRound( t / ((double)cvGetTickFrequency() * 1000.0) );
    nFaces = rects->total;
    //printf("Face Detection took %d ms and found %d objects\n", ms, nFaces);
    // Get the first detected face (the biggest).
    if (nFaces > 0)
        rc = *(CvRect*)cvGetSeqElem( rects, 0 );
    else
        rc = cvRect(-1,-1,-1,-1); // Couldn't find the face.

    if (greyImg)
    {
        cvReleaseImage( &greyImg );
    }
    cvReleaseMemStorage( &storage );
    return rc; // Return the biggest face found, or (-1,-1,-1,-1).
}